package com.ljb.android.comm.router

import android.os.Bundle
import android.text.TextUtils
import com.google.gson.JsonObject
import com.ljb.android.comm.utils.UrlUtils
import com.ljb.android.comm.utils.XLog
import net.ljb.kt.utils.JsonParser
import java.net.URLDecoder

class SchemeHelper {

    fun createSchemeUrl(routerAction: RouterAction): String {
        var result = ""
        try {
            result = StringBuilder(RouterConfig.Scheme.run { "$SCHEME$HOST$PATH" })
                .append("?")
                .append(RouterConfig.Scheme.ACTION)
                .append("=")
                .append(JsonParser.toJson(routerAction))
                .toString()
            XLog.i("createUrl:: $result")
        } catch (e: Exception) {
            XLog.e(e)
        }

        return result
    }

    /**
     * Scheme 路由跳转
     * */
    fun jumpUrl(
        jumpUrl: String?,
        callBack: ((action: RouterAction, result: String) -> Unit)? = null
    ) {
        //TODO callBack 待开发
        try {
            XLog.i("jumpUrl:: $jumpUrl")
            //校验协议
            if (TextUtils.isEmpty(jumpUrl)) return
            val schemeUrl = RouterConfig.Scheme.run { "$SCHEME$HOST$PATH" }
            if (jumpUrl!!.startsWith(schemeUrl)) {
                var actionJson = UrlUtils.getUrlParam(jumpUrl, RouterConfig.Scheme.ACTION)
                actionJson = URLDecoder.decode(actionJson)
                val routerAction = JsonParser.fromJsonObj(actionJson, RouterAction::class.java)
                dispatchAction(routerAction)
            }
        } catch (e: Exception) {
            XLog.e(e)
        }
    }

    /**
     * 根据action_type分发路由
     * */
    private fun dispatchAction(routerAction: RouterAction) {
        if (TextUtils.isEmpty(routerAction.action_type)) return
        when (routerAction.action_type) {
            RouterConfig.Scheme.ACTION_TYPE_JUMP -> {
                // 跳转页面
                jumpPage(routerAction)
            }
            RouterConfig.Scheme.ACTION_TYPE_CALL -> {
                // 调用功能
                callAction(routerAction)
            }
            else -> {
                XLog.e("未知行为类型（action_type）：：${routerAction.action_type}")
            }
        }
    }

    /**
     * 调起功能
     * */
    private fun callAction(routerAction: RouterAction) {
        if (TextUtils.isEmpty(routerAction.path)) return
        RouterManager.getService(routerAction.path!!)
    }

    /**
     * 跳转页面
     * */
    private fun jumpPage(routerAction: RouterAction) {
        if (TextUtils.isEmpty(routerAction.page_type) || TextUtils.isEmpty(routerAction.path)) return

        when (routerAction.page_type) {
            RouterConfig.Scheme.PAGE_TYPE_NATIVE -> {
                // 原生页面
                RouterManager.goActivity(routerAction.path!!, getParams(routerAction.params))
            }
            RouterConfig.Scheme.PAGE_TYPE_WEB -> {
                // H5
                RouterManager.goActivity(routerAction.path!!, getParams(routerAction.params))
            }
            RouterConfig.Scheme.PAGE_TYPE_RN -> {
                // RN

            }
            else -> {
                XLog.e("未知页面类型（page_type）：：${routerAction.page_type}")
            }
        }
    }


    private fun getParams(params: JsonObject?): Bundle? {
        if (params == null || params.size() == 0) return null
        val bundle = Bundle()
        val keySet = params.keySet()
        keySet.forEach {
            bundle.putString(it, params.get(it).asString)
        }
        return bundle
    }


//    private fun getParams(params: String?): Bundle? {
//        if (TextUtils.isEmpty(params)) return null
//        val bundle = Bundle()
//        val jsonObject = JSONObject(params!!)
//        val keySet = jsonObject.keys()
//        keySet.forEach {
//            bundle.putString(it, jsonObject.getString(it))
//        }
//        return bundle
//    }

    /*
    // host  ： 业务线
    // path1 ： 项目
    // path2 :  入口
    // action : 路由协议
    ercar://com.wuba.ercar/openApp?action="{
        "action_type" : "jump / call",            // 动作类型  跳转 或 功能
        "page_type" : "native / web",             // 跳转的页面类型
        "path" :  "/search/SearchActivity",       // 开发中的实际路由
        "params" : "{ "key" : "kotlin" }"         // 页面参数 或 功能参数
     }"

    wandroid://com.ljb.android.component/openApp?action={ "action_type":"jump" , "page_type":"native" , "path":"/search/SearchActivity" , "params":"{ \"key\" : \"kotlin\" }"}
*/

}